﻿using System;
using System.Web;
using System.Collections.Generic;
using System.Text;
using System.Web.UI.WebControls;
using System.Web.UI;
using System.ComponentModel;
using System.Web.Caching;
using System.Web.UI.HtmlControls;

namespace YhmOA.Pager
{
    [Serializable]
    [ToolboxData("<{0}:Pager runat=server></{0}:Pager>")]
    [Designer(typeof(PagerDesgining))]
    public class Pager : WebControl, INamingContainer, IPostBackEventHandler
    {
        public delegate void BindDataSourcesHandler(object sender, PagerEventArgs e);
        public delegate Data GetDataMethod(int pageIndex, int pageSize);

        public event BindDataSourcesHandler BindDataSources;

        #region 获取数据源的方法
        /// <summary>
        /// <para>获取数据源的方法</para>
        /// <para>方法有两个参数</para>
        /// <para>第一个是PageIndex</para>
        /// <para>第二个是PageSize</para>
        /// </summary>
        public GetDataMethod GetDataMethoder { get; set; }
        #endregion

        #region 获取或设置当前页的页码
        /// <summary>
        /// 获取和设置当前页的页码
        /// </summary>
        public int PageIndex
        {
            get
            {
                if (ViewState["____PageIndex"] == null)
                {
                    ViewState["____PageIndex"] = 1;
                }
                return Convert.ToInt32(ViewState["____PageIndex"]);
            }
            set
            {
                if (value < 1)
                {
                    ViewState["____PageIndex"] = 1;
                }
                else
                {
                    ViewState["____PageIndex"] = value;
                }
            }
        }
        #endregion

        #region 获取或设置当前页的大小
        /// <summary>
        /// 获取或设置当前页的大小
        /// </summary>
        public int PageSize
        {
            get
            {
                if (ViewState["____PageSize"] == null)
                {
                    ViewState["____PageSize"] = 1;
                }
                return Convert.ToInt32(ViewState["____PageSize"]);
            }
            set
            {
                if (value < 1)
                {
                    ViewState["____PageSize"] = 1;
                }
                else
                {
                    ViewState["____PageSize"] = value;
                }
            }
        }
        #endregion

        #region 获取或设置总记录数
        /// <summary>
        /// 获取或设置总记录数
        /// </summary>
        public int PageAllCount
        {
            get
            {
                if (ViewState["____PageAllCount"] == null)
                {
                    ViewState["____PageAllCount"] = 0;
                }
                return Convert.ToInt32(ViewState["____PageAllCount"]);
            }
            set
            {
                ViewState["____PageAllCount"] = value;
            }
        }
        #endregion

        #region 获取或设置总页数
        /// <summary>
        /// 获取或设置总页数
        /// </summary>
        public int PageCount
        {
            get
            {
                return Convert.ToInt32(Math.Floor(Convert.ToDecimal((this.PageAllCount + this.PageSize - 1) / this.PageSize)));
            }
        }
        #endregion

        #region 获取或设置页面显示页码的开始值
        /// <summary>
        /// 获取或设置页面显示页码的开始值
        /// </summary>
        public int PageStart
        {
            get
            {
                if (ViewState["____PageStart"] == null)
                {
                    ViewState["____PageStart"] = 1;
                }
                return Convert.ToInt32(ViewState["____PageStart"]);
            }
            set
            {
                ViewState["____PageStart"] = value;
            }
        }
        #endregion

        #region 获取或设置页面显示页码的终止值
        /// <summary>
        /// 获取或设置页面显示页码的终止值
        /// </summary>
        public int PageStop
        {
            get
            {
                if (ViewState["____PageStop"] == null)
                {
                    ViewState["____PageStop"] = 1;
                }
                return Convert.ToInt32(ViewState["____PageStop"]);
            }
            set
            {
                ViewState["____PageStop"] = value;
            }
        }
        #endregion

        #region 获取或设置页面显示页码的位数
        /// <summary>
        /// 获取或设置页面显示页码的位数
        /// </summary>
        public int PageShow
        {
            get
            {
                if (ViewState["____PageShow"] == null)
                {
                    ViewState["____PageShow"] = 5;
                }
                return Convert.ToInt32(ViewState["____PageShow"]);
            }
            set
            {
                ViewState["____PageShow"] = value;
            }
        }
        #endregion

        #region 获取或设置排序的字段
        /// <summary>
        /// 获取或设置排序的字段
        /// </summary>
        public string OrderName
        {
            get
            {
                if (ViewState["____OrderName"] == null)
                {
                    ViewState["____OrderName"] = "ID";
                }
                return ViewState["____OrderName"].ToString();
            }
            set
            {
                this.SortOrder = this.SortOrder.Trim().ToLower() == "asc" ? "desc" : "asc";
                ViewState["____OrderName"] = value;
            }
        }
        #endregion

        #region 获取或设置排序的顺序
        /// <summary>
        /// 获取或设置排序的顺序
        /// </summary>
        public string SortOrder
        {
            get
            {
                if (ViewState["____SortOrder"] == null)
                {
                    ViewState["____SortOrder"] = "desc";
                }
                return " " + ViewState["____SortOrder"].ToString();
            }
            set
            {
                ViewState["____SortOrder"] = value;
            }
        }
        #endregion

        protected override void CreateChildControls()
        {
            this.Page.ClientScript.GetPostBackEventReference(this.Page, "");
        }

        #region 获取控件在客户端生成的代码
        /// <summary>
        /// 获取控件在客户端生成的代码
        /// </summary>
        /// <returns></returns>
        private string GetPagerRenderString()
        {
            StringBuilder builder = new StringBuilder();
            string format = "<a class=\"{0}\" onclick=\"__doPostBack('" + this.UniqueID + "','{1}');\">{2}</a>";
            builder.Append("<div id=\"" + this.ClientID + "\" class=\"Pager\">");
            builder.Append(String.Format(format, "PageButton", 1, "首页"));
            int numbefore = (this.PageIndex - this.PageShow);
            if (numbefore < 1)
            {
                numbefore = 1;
            }
            builder.Append(String.Format(format, "PageButton", numbefore, "<<"));
            for (int i = this.PageStart; i <= this.PageStop; i++)
            {
                builder.Append(String.Format(format, i == this.PageIndex ? "PageIndexNumber" : "PageNumber", i.ToString(), i.ToString()));
            }
            int numAfter = this.PageIndex + this.PageShow;
            if (numAfter > this.PageCount)
            {
                numAfter = this.PageCount;
            }
            builder.Append(String.Format(format, "PageButton", numAfter, ">>"));
            builder.Append(String.Format(format, "PageButton", this.PageCount, "末页"));
            builder.Append("<span class=\"PageSpan\">当前第</span><input type=\"text\" id=\"pageIndex\" name=\"pageIndex\" class=\"PageTextBox\" value=\"" + this.PageIndex + "\" onchange=\"__doPostBack('" + this.UniqueID + "', '');\" />");
            builder.Append("<span class=\"PageSpan\">页，每页</span><input type=\"text\" id=\"pageSize\" name=\"pageSize\" class=\"PageTextBox\" value=\"" + this.PageSize + "\" onchange=\"__doPostBack('" + this.UniqueID + "', '');\" />");
            builder.Append("<span class=\"PageSpan\">条记录，共" + this.PageCount.ToString() + "页" + this.PageAllCount.ToString() + "条记录</span></div>");
            return builder.ToString();
        }
        #endregion

        public void RaisePostBackEvent(string eventArgument)
        {
            if (eventArgument != null && eventArgument != "")
            {
                this.PageIndex = Convert.ToInt32(eventArgument);
            }
            this.BindDataHandle();
        }

        public void OnBindDataSources(object sender, PagerEventArgs e)
        {
            if (this.BindDataSources != null)
            {
                this.BindDataSources(sender, e);
            }
        }

        #region 重写OnLoad事件
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            string pageIndex = HttpContext.Current.Request["pageIndex"] ?? "1";
            string pageSize = HttpContext.Current.Request["pageSize"] ?? "15";
            try
            {
                this.PageIndex = Convert.ToInt32(pageIndex);
                this.PageSize = Convert.ToInt32(pageSize);
            }
            catch
            {
                this.PageIndex = 1;
                this.PageSize = 10;
            }
            if (!this.Page.IsPostBack)
            {
                this.BindDataHandle();
            }
        }
        #endregion

        #region 数据绑定
        /// <summary>
        /// 数据绑定
        /// </summary>
        private void BindDataHandle()
        {
            if (this.GetDataMethoder != null)
            {
                if (this.PageIndex > this.PageCount)
                {
                    this.PageIndex = this.PageCount;
                }
                Data data = this.GetDataMethoder(this.PageIndex, this.PageSize);
                this.PageAllCount = data.Count;
                if (this.PageIndex < 1)
                {
                    this.PageIndex = 1;
                }
                if (this.PageIndex > this.PageCount)
                {
                    this.PageIndex = this.PageCount;
                }
                this.PageStart = Convert.ToInt32(Math.Floor(Convert.ToDouble((this.PageIndex - 1) / this.PageShow))) * this.PageShow;
                this.PageStart++;
                this.PageStop = (this.PageStart + this.PageShow) - 1;
                if (this.PageStart < 1)
                {
                    this.PageStart = 1;
                }
                if (this.PageStop > this.PageCount)
                {
                    this.PageStop = this.PageCount;
                }
                this.OnBindDataSources(this, new PagerEventArgs(data.DataSources, this.PageIndex));
            }
        }
        #endregion

        #region 重新绑定事件
        /// <summary>
        /// 重新绑定事件
        /// </summary>
        public void Rebind()
        {
            this.BindDataHandle();
        }
        #endregion

        #region 重写OnPreRender事件
        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            HtmlLink style = new HtmlLink();
            style.Href = this.Page.ClientScript.GetWebResourceUrl(base.GetType(), "YhmOA.Pager.style.css");
            style.Attributes.Add("rel", "stylesheet");
            style.Attributes.Add("type", "text/css");
            this.Page.Header.Controls.Add(style);
        }
        #endregion

        #region 重写Render事件
        protected override void Render(HtmlTextWriter writer)
        {
            writer.Write(GetPagerRenderString());
        }
        #endregion

        #region 获取缓存中的数据
        /// <summary>
        /// 获取缓存中的数据
        /// </summary>
        /// <param name="key">缓存的键</param>
        /// <returns>返回缓存中的数据</returns>
        private object GetCache(string key)
        {
            return this.Page.Cache.Get(key);
        }
        #endregion

        #region 设置缓存
        /// <summary>
        /// 设置缓存
        /// </summary>
        /// <param name="key">缓存的键</param>
        /// <param name="value">要放进缓存中的值</param>
        private void SetCache(string key, object value)
        {
            this.Page.Cache.Insert(key, value, null, DateTime.Now.AddMinutes(Convert.ToDouble(this.Page.Session.Timeout)), Cache.NoSlidingExpiration, CacheItemPriority.Normal, null);
        }
        #endregion
    }

    /// <summary>
    /// 分页控件的数据源
    /// </summary>
    [Serializable]
    public class Data
    {
        private int count;
        private object dataSources;

        /// <summary>
        /// 本次获取的数据
        /// </summary>
        public object DataSources
        {
            get { return dataSources; }
            set { dataSources = value; }
        }

        /// <summary>
        /// 记录的条数
        /// </summary>
        public int Count
        {
            get { return count; }
            set { count = value; }
        }

        /// <summary>
        /// 空构造
        /// </summary>
        public Data() { }

        /// <summary>
        /// 带参数构造
        /// </summary>
        /// <param name="count">记录的条数</param>
        /// <param name="dataSources">本次获取的数据</param>
        public Data(int count, object dataSources)
        {
            this.count = count;
            this.dataSources = dataSources;
        }
    }
}
